﻿$(function () {
    // 图表实例集合
    const chartInstances = {};

    // 确保数据管理器存在
    if (!window.weatherDataManager) {
        console.error('WeatherDataManager 未初始化，使用默认数据');
        initAllChartsWithoutObserver();
        return;
    }

    // 初始化所有图表
    function initAllCharts() {
        console.log('开始初始化所有图表...');

        chartInstances.echart1 = initEchart1();
        chartInstances.echart2 = initEchart2();
        chartInstances.echart3 = initEchart3();
        chartInstances.echart4 = initEchart4();
        chartInstances.echart5 = initEchart5();
        chartInstances.echart6 = initEchart6();

        // 注册为观察者
        const chartObserver = {
            update: function(district, date, chartData) {
                console.log('图表观察者收到更新通知:', district, date, chartData);
                updateAllCharts(district, date, chartData);
            }
        };

        window.weatherDataManager.addObserver(chartObserver);
        console.log('图表观察者注册完成');
    }

    // 更新所有图表
    function updateAllCharts(district, date, chartData) {
        if (!district || !chartData) {
            console.log('未指定区域或数据，保持默认数据');
            return;
        }

        console.log('开始更新所有图表，区域:', district, '数据:', chartData);

        try {
            // 更新各个图表 - 直接使用传入的chartData，不要重新获取
            updateEchart1(chartInstances.echart1, chartData, district);
            updateEchart2(chartInstances.echart2, chartData, district);
            updateEchart4(chartInstances.echart4, chartData, district);
            updateEchart5(chartInstances.echart5, chartData, district);
            updateEchart6(chartInstances.echart6, chartData, district);

            // 更新echart3的生活指数
            updateEchart3(district, chartData);

            console.log('所有图表更新完成');
        } catch (error) {
            console.error('更新图表数据失败:', error);
        }
    }

    // 无观察者模式初始化
    function initAllChartsWithoutObserver() {
        console.log('使用无观察者模式初始化图表');
        chartInstances.echart1 = initEchart1();
        chartInstances.echart2 = initEchart2();
        chartInstances.echart3 = initEchart3();
        chartInstances.echart4 = initEchart4();
        chartInstances.echart5 = initEchart5();
        chartInstances.echart6 = initEchart6();
    }

    // 根据情况选择初始化方式
    if (window.weatherDataManager) {
        console.log('使用数据管理器初始化图表');
        initAllCharts();
    } else {
        console.log('使用默认数据初始化图表');
        initAllChartsWithoutObserver();
    }

    console.log('图表初始化完成');

    // 初始化图表1（风速风向）
    function initEchart1() {
        var myChart = echarts.init(document.getElementById('echart1'));

        // 使用默认数据初始化
        const defaultWindSpeedData = [2.9, 6.7, 5.9, 3.5, 6.4, 6.8, 9.3, 10.9, 7.8, 4.2, 15.0, 10.5,
            9.4, 10.4, 17.8, 10.3, 10.5, 10.3, 6.3, 10.7, 11.3, 3.8, 7.1, 3.4];
        const defaultWindDirectionData = ['南', '东南', '北', '南', '西北', '东', '东北', '东南',
            '北', '南', '西北', '北', '东', '东北', '西', '西北', '西', '西', '东北', '西南', '南',
            '西北', '西南', '西南'];

        const option = getEchart1Option(defaultWindSpeedData, defaultWindDirectionData, '郑州市');
        myChart.setOption(option);

        window.addEventListener("resize", function(){
            myChart.resize();
        });

        return myChart;
    }

    // 获取图表1的配置选项
    function getEchart1Option(windSpeedData, windDirectionData, district) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    lineStyle: {
                        color: '#dddc6b'
                    }
                },
                formatter: function(params) {
                    var data = params[0];
                    var index = params[0].dataIndex;
                    var direction = windDirectionData[index];
                    return `
                    <div style="text-align: center; padding: 8px;">
                        <div style="font-weight: bold; color: #fff; margin-bottom: 5px;">
                            ${district} - ${data.name}:00 时
                        </div>
                        <div style="color: #00a8ff; font-size: 16px; margin: 5px 0;">
                           风速: ${data.value} m/s
                        </div>
                        <div style="color: #00a8ff; font-size: 16px; margin: 5px 0;">
                            风向: ${direction}
                        </div>
                    </div>
                `;
                }
            },
            grid: {
                left: '10',
                top: '20',
                right: '10',
                bottom: '10',
                containLabel: true
            },
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.2)'
                    }
                },
                data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
            }],
            yAxis: [{
                type: 'value',
                max: 25,
                axisTick: {show: false},
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                },
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                }
            }],
            series: [
                {
                    name: '风速',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 5,
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            color: '#00a8ff',
                            width: 2
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(0,168,255,0.4)'
                            }, {
                                offset: 0.8,
                                color: 'rgba(0,168,255,0.1)'
                            }], false),
                            shadowColor: 'rgba(0, 0, 0, 0.1)',
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#00a8ff',
                            borderColor: 'rgba(221, 220, 107, .1)',
                            borderWidth: 12
                        }
                    },
                    data: windSpeedData
                }
            ]
        };
    }

    // 更新图表1
    function updateEchart1(chartInstance, chartData, district) {
        if (!chartData || !chartData.windSpeed || !chartData.windDirection) {
            console.warn('风速数据不完整，保持原有数据', {
                hasChartData: !!chartData,
                hasWindSpeed: !!chartData?.windSpeed,
                hasWindDirection: !!chartData?.windDirection,
                windSpeedLength: chartData?.windSpeed?.length,
                windDirectionLength: chartData?.windDirection?.length
            });
            return;
        }

        // 验证数据合理性
        const validWindSpeed = chartData.windSpeed.map(speed => {
            const num = parseFloat(speed);
            return isNaN(num) || num < 0 ? 2 + Math.random() * 5 : Math.min(num, 25);
        });

        const validWindDirection = chartData.windDirection.map(dir => {
            return dir && typeof dir === 'string' ? dir : '北';
        });

        console.log('更新风速图表，数据:', {
            windSpeed: validWindSpeed,
            windDirection: validWindDirection,
            district: district
        });

        const option = getEchart1Option(validWindSpeed, validWindDirection, district);
        chartInstance.setOption(option, true);
    }

    // 初始化图表2（气压）
    function initEchart2() {
        var myChart = echarts.init(document.getElementById('echart2'));

        const defaultPressureData = [1015.6, 1010.6, 1013.8, 1012.2, 1015.1, 1010.3, 1009.6, 1010.8, 1014.0,
            1013.6, 1011.2, 1011.9, 1010.3, 1012.9, 1012.4, 1013.4, 1010.9, 1013.2, 1008.5, 1011.0, 1009.1, 1012.1, 1014.4, 1010.9];

        const option = getEchart2Option(defaultPressureData, '郑州市');
        myChart.setOption(option);

        window.addEventListener("resize", function(){
            myChart.resize();
        });

        return myChart;
    }

    function getEchart2Option(pressureData, district) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    lineStyle: {
                        color: '#dddc6b'
                    }
                },
                formatter: function(params) {
                    var data = params[0];
                    var level = data.value < 990 ? '低压' : data.value < 1010 ? '正常' : '高压';
                    return `
                    <div style="text-align: center; padding: 8px;">
                        <div style="font-weight: bold; color: #fff; margin-bottom: 5px;">
                            ${district} - ${data.name}:00 时
                        </div>
                        <div style="color: #00d887; font-size: 16px; margin: 5px 0;">
                            ${data.value} hPa
                        </div>
                        <div style="color: #ccc; font-size: 12px;">
                            气压等级: ${level}
                        </div>
                    </div>
                `;
                }
            },
            grid: {
                left: '10',
                top: '20',
                right: '10',
                bottom: '10',
                containLabel: true
            },
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.2)'
                    }
                },
                data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
            }],
            yAxis: [{
                type: 'value',
                min: 1000,
                axisTick: {show: false},
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                },
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                }
            }],
            series: [
                {
                    name: '气压',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 5,
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            color: '#00d887',
                            width: 2
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(0, 216, 135, 0.4)'
                            }, {
                                offset: 0.8,
                                color: 'rgba(0, 216, 135, 0.1)'
                            }], false),
                            shadowColor: 'rgba(0, 0, 0, 0.1)',
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#00d887',
                            borderColor: 'rgba(221, 220, 107, .1)',
                            borderWidth: 12
                        }
                    },
                    data: pressureData
                }
            ]
        };
    }

    function updateEchart2(chartInstance, chartData, district) {
        if (!chartData || !chartData.pressure) {
            console.warn('气压数据不完整，保持原有数据', {
                hasChartData: !!chartData,
                hasPressure: !!chartData?.pressure,
                pressureLength: chartData?.pressure?.length
            });
            return;
        }

        // 验证数据合理性
        const validPressure = chartData.pressure.map(pressure => {
            const num = parseFloat(pressure);
            return isNaN(num) ? 1010 + Math.random() * 10 : Math.max(1000, Math.min(num, 1020));
        });

        console.log('更新气压图表，数据:', {
            pressure: validPressure,
            district: district
        });

        const option = getEchart2Option(validPressure, district);
        chartInstance.setOption(option, true);
    }

    // 初始化图表3（生活指数）
    function initEchart3() {
        var container = document.getElementById('echart3');
        let defaultChartData = null;

        // 安全地获取默认数据
        if (window.weatherDataManager && typeof window.weatherDataManager.generateChartData === 'function') {
            try {
                const today = new Date();
                const dateString = today.toISOString().split('T')[0];
                defaultChartData = window.weatherDataManager.generateChartData('郑州市', dateString);
            } catch (error) {
                console.warn('获取生活指数默认数据失败:', error);
            }
        }

        createEchart3Grid(container, '郑州市', defaultChartData);
        return container;
    }

    function createEchart3Grid(container, district, chartData) {
        // 清空容器
        container.innerHTML = '';

        // 创建网格布局容器
        var gridContainer = document.createElement('div');
        gridContainer.style.display = 'grid';
        gridContainer.style.gridTemplateColumns = 'repeat(3, 1fr)';
        gridContainer.style.gridTemplateRows = 'repeat(2, 1fr)';
        gridContainer.style.gap = '10px';
        gridContainer.style.width = '100%';
        gridContainer.style.height = '100%';
        gridContainer.style.padding = '10px';
        gridContainer.style.boxSizing = 'border-box';

        // 根据随机数据生成生活指数建议
        function generateLivingIndex(chartData) {
            // 完全随机生成，不依赖传入的 chartData

            // 穿衣建议选项
            const dressOptions = [
                { suggestion: '宜穿短袖', image: 'images/yichuanduanxiu.jpg' },
                { suggestion: '宜穿长袖', image: 'images/yichuanchangxiu.jpg' },
                { suggestion: '宜穿外套', image: 'images/yichuanwaitao.jpg' }
            ];

            // 洗车建议选项
            const carWashOptions = [
                { suggestion: '不宜洗车', image: 'images/buyixiche.jpg' },
                { suggestion: '宜洗车', image: 'images/yixiche.jpg' }
            ];

            // 防晒建议选项
            const sunscreenOptions = [
                { suggestion: '需涂防晒', image: 'images/xvtufangshai.jpg' },
                { suggestion: '无需防晒', image: 'images/wuxvfangshai.jpg' }
            ];

            // 带伞建议选项
            const umbrellaOptions = [
                { suggestion: '有雨带伞', image: 'images/youyvdaisan.jpg' },
                { suggestion: '防晒带伞', image: 'images/fangshaidaisan.jpg' },
                { suggestion: '无需带伞', image: 'images/wuxvdaisan.jpg' }
            ];

            // 生病提醒选项
            const illnessOptions = [
                { suggestion: '极易感冒', image: 'images/jiyiganmao.jpg' },
                { suggestion: '较易感冒', image: 'images/jiaoyiganmao.jpg' },
                { suggestion: '少发感冒', image: 'images/shaofaganmao.jpg' }
            ];

            // 运动建议选项
            const exerciseOptions = [
                { suggestion: '宜室内运动', image: 'images/yishineiyundong.jpg' },
                { suggestion: '宜室外运动', image: 'images/yishiwaiyundong.jpg' }
            ];

            // 随机选择各项建议
            const randomDress = dressOptions[Math.floor(Math.random() * dressOptions.length)];
            const randomCarWash = carWashOptions[Math.floor(Math.random() * carWashOptions.length)];
            const randomSunscreen = sunscreenOptions[Math.floor(Math.random() * sunscreenOptions.length)];
            const randomUmbrella = umbrellaOptions[Math.floor(Math.random() * umbrellaOptions.length)];
            const randomIllness = illnessOptions[Math.floor(Math.random() * illnessOptions.length)];
            const randomExercise = exerciseOptions[Math.floor(Math.random() * exerciseOptions.length)];

            return [
                {
                    title: '穿衣建议',
                    imageUrl: randomDress.image,
                    description: randomDress.suggestion
                },
                {
                    title: '洗车建议',
                    imageUrl: randomCarWash.image,
                    description: randomCarWash.suggestion
                },
                {
                    title: '防晒建议',
                    imageUrl: randomSunscreen.image,
                    description: randomSunscreen.suggestion
                },
                {
                    title: '带伞建议',
                    imageUrl: randomUmbrella.image,
                    description: randomUmbrella.suggestion
                },
                {
                    title: '生病提醒',
                    imageUrl: randomIllness.image,
                    description: randomIllness.suggestion
                },
                {
                    title: '运动建议',
                    imageUrl: randomExercise.image,
                    description: randomExercise.suggestion
                }
            ];
        }

        // 默认生活指数
        function getDefaultLivingIndex() {
            return [
                {
                    title: '穿衣建议',
                    imageUrl: 'images/yichuanwaitao.jpg',
                    description: '宜穿外套'
                },
                {
                    title: '洗车建议',
                    imageUrl: 'images/buyixiche.jpg',
                    description: '不宜洗车'
                },
                {
                    title: '防晒建议',
                    imageUrl: 'images/wuxvfangshai.jpg',
                    description: '无需防晒'
                },
                {
                    title: '带伞建议',
                    imageUrl: 'images/youyvdaisan.jpg',
                    description: '有雨带伞'
                },
                {
                    title: '生病提醒',
                    imageUrl: 'images/shaofaganmao.jpg',
                    description: '少发感冒'
                },
                {
                    title: '运动建议',
                    imageUrl: 'images/yishineiyundong.jpg',
                    description: '宜室内运动'
                }
            ];
        }

        // 获取生活指数数据
        const gridData = chartData ? generateLivingIndex(chartData) : getDefaultLivingIndex();

        // 创建六个格子
        gridData.forEach((item, index) => {
            var gridItem = document.createElement('div');
            gridItem.style.border = '1px solid rgba(255,255,255,0.2)';
            gridItem.style.borderRadius = '5px';
            gridItem.style.display = 'flex';
            gridItem.style.flexDirection = 'column';
            gridItem.style.alignItems = 'center';
            gridItem.style.justifyContent = 'space-between';
            gridItem.style.padding = '10px';
            gridItem.style.background = 'rgba(255,255,255,0.05)';
            gridItem.style.color = 'rgba(255,255,255,0.8)';

            // 设置格子位置
            if (index < 3) {
                gridItem.style.gridColumn = index + 1;
                gridItem.style.gridRow = '1';
            } else {
                gridItem.style.gridColumn = index - 2;
                gridItem.style.gridRow = '2';
            }

            // 创建标题部分
            var titleContainer = document.createElement('div');
            titleContainer.style.flex = '1';
            titleContainer.style.textAlign = 'center';
            titleContainer.style.display = 'flex';
            titleContainer.style.alignItems = 'center';
            titleContainer.style.justifyContent = 'center';

            var title = document.createElement('div');
            title.textContent = item.title;
            title.style.fontSize = '14px';
            title.style.fontWeight = 'bold';
            title.style.color = '#27d08a';
            titleContainer.appendChild(title);

            // 创建图片部分
            var imgContainer = document.createElement('div');
            imgContainer.style.flex = '3';
            imgContainer.style.display = 'flex';
            imgContainer.style.alignItems = 'center';
            imgContainer.style.justifyContent = 'center';
            imgContainer.style.width = '100%';
            imgContainer.style.height = '100%';

            var img = document.createElement('img');
            img.src = item.imageUrl;
            img.alt = item.title;
            img.style.width = '40px';
            img.style.height = '40px';
            img.style.objectFit = 'cover';
            img.style.borderRadius = '3px';
            img.style.maxWidth = '100%';
            img.style.maxHeight = '100%';

            // 添加错误处理
            img.onerror = function() {
                this.style.display = 'none';
            };

            imgContainer.appendChild(img);

            // 创建描述部分
            var descContainer = document.createElement('div');
            descContainer.style.flex = '1';
            descContainer.style.textAlign = 'center';
            descContainer.style.display = 'flex';
            descContainer.style.alignItems = 'center';
            descContainer.style.justifyContent = 'center';

            var desc = document.createElement('div');
            desc.textContent = item.description;
            desc.style.fontSize = '10px';
            desc.style.color = 'rgba(255,255,255,0.6)';
            descContainer.appendChild(desc);

            // 将元素添加到格子中
            gridItem.appendChild(titleContainer);
            gridItem.appendChild(imgContainer);
            gridItem.appendChild(descContainer);

            gridContainer.appendChild(gridItem);
        });

        container.appendChild(gridContainer);
    }

    function updateEchart3(district, chartData) {
        var container = document.getElementById('echart3');

        // 如果容器已存在内容，可以只更新数据而不是重建
        const existingGrid = container.querySelector('.living-index-grid');
        if (existingGrid) {
            updateExistingGrid(existingGrid, district, chartData);
        } else {
            createEchart3Grid(container, district, chartData);
        }
    }

    // 初始化图表4（温度）
    function initEchart4() {
        var myChart = echarts.init(document.getElementById('echart4'));

        const defaultTemperatureData = [12.4, 12.4, 13.2, 12.0, 11.5, 13.1, 12.8, 12.2, 12.9, 13.0, 13.8, 13.6,
            15.2, 15.1, 13.9, 13.9, 13.9, 14.3, 15.1, 13.5, 14.0, 13.9, 13.1, 14.2];

        const option = getEchart4Option(defaultTemperatureData, '郑州市');
        myChart.setOption(option);

        window.addEventListener("resize", function(){
            myChart.resize();
        });

        return myChart;
    }

    function getEchart4Option(temperatureData, district) {
        const minTemp = Math.min(...temperatureData);
        const maxTemp = Math.max(...temperatureData);
        const rangeMin = Math.floor(minTemp) - 1;
        const rangeMax = Math.ceil(maxTemp) + 1;

        function getTemperatureColor(temp) {
            if (temp >= 0 && temp < 10) {
                return '#1e3a8a';
            } else if (temp >= 10 && temp < 20) {
                return '#3b82f6';
            } else if (temp >= 20 && temp < 30) {
                return '#10b981';
            } else if (temp >= 30 && temp <= 40) {
                return '#ef4444';
            } else {
                return '#ffffff';
            }
        }

        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    lineStyle: {
                        color: '#dddc6b'
                    }
                },
                formatter: function(params) {
                    var data = params[0];
                    var tempColor = getTemperatureColor(data.value);
                    return `
                <div style="text-align: center; padding: 8px;">
                    <div style="font-weight: bold; color: #fff; margin-bottom: 5px;">
                        ${district} - ${data.name}:00 时
                    </div>
                    <div style="color: ${tempColor}; font-size: 16px; margin: 5px 0;">
                        ${data.value} °C
                    </div>
                </div>
            `;
                }
            },
            grid: {
                left: '10',
                top: '20',
                right: '10',
                bottom: '10',
                containLabel: true
            },
            visualMap: {
                type: 'continuous',
                min: rangeMin,
                max: rangeMax,
                dimension: 1,
                calculable: true,
                orient: 'vertical',
                right: '0',
                top: 'center',
                textStyle: {
                    color: '#fff'
                },
                inRange: {
                    color: ['#4cbffc', '#ff0110']
                },
                show: false
            },
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.2)'
                    }
                },
                data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
                    '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
            }],
            yAxis: [{
                type: 'value',
                axisTick: {show: false},
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                },
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                }
            }],
            series: [
                {
                    name: '温度',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 5,
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            width: 2
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(255, 255, 255, 0.4)'
                            }, {
                                offset: 0.8,
                                color: 'rgba(255, 0, 0, 0.1)'
                            }], false),
                            shadowColor: 'rgba(0, 0, 0, 0.1)',
                        }
                    },
                    itemStyle: {
                        normal: {
                            borderColor: 'rgba(221, 220, 107, .1)',
                            borderWidth: 12
                        }
                    },
                    data: temperatureData
                }
            ]
        };
    }

    function updateEchart4(chartInstance, chartData, district) {
        if (!chartData || !chartData.temperature) {
            console.warn('温度数据不完整，保持原有数据', {
                hasChartData: !!chartData,
                hasTemperature: !!chartData?.temperature,
                temperatureLength: chartData?.temperature?.length
            });
            return;
        }

        // 验证数据合理性
        const validTemperature = chartData.temperature.map(temp => {
            const num = parseFloat(temp);
            return isNaN(num) ? 20 + Math.random() * 10 : Math.max(10, Math.min(num, 35));
        });

        console.log('更新温度图表，数据:', {
            temperature: validTemperature,
            district: district
        });

        const option = getEchart4Option(validTemperature, district);
        chartInstance.setOption(option, true);
    }

    // 初始化图表5（降水量）
    function initEchart5() {
        var myChart = echarts.init(document.getElementById('echart5'));

        const defaultPrecipitationData = [0.55, 0.19, 0.25, 0.16, 0.16, 0.27, 0.45, 0.40, 1.00, 1.73, 1.88, 2.41,
            3.17, 1.73, 5.25, 4.01, 2.09, 2.94, 1.26, 1.28, 1.01, 0.43, 0.60];

        const option = getEchart5Option(defaultPrecipitationData, '郑州市');
        myChart.setOption(option);

        window.addEventListener("resize", function(){
            myChart.resize();
        });

        return myChart;
    }

    function getEchart5Option(precipitationData, district) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    var data = params[0];
                    return `
                    <div style="text-align: center; padding: 8px;">
                        <div style="font-weight: bold; color: #fff; margin-bottom: 5px;">
                            ${district} - ${data.name}:00 时
                        </div>
                        <div style="color: #2f89cf; font-size: 16px; margin: 5px 0;">
                           降水量: ${data.value} mm
                        </div>
                    </div>
                `;
                }
            },
            grid: {
                left: '0%',
                top:'10px',
                right: '0%',
                bottom: '2%',
                containLabel: true
            },
            xAxis: [{
                type: 'category',
                data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
                    '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(255,255,255,.1)",
                        width: 1,
                        type: "solid"
                    },
                },
                axisTick: {
                    show: false,
                },
                axisLabel:  {
                    interval: 0,
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize: '12',
                    },
                },
            }],
            yAxis: [{
                type: 'value',
                axisLabel: {
                    show:true,
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize: '12',
                    },
                },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(255,255,255,.1)",
                        width: 1,
                        type: "solid"
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: "rgba(255,255,255,.1)",
                    }
                }
            }],
            series: [{
                type: 'bar',
                data: precipitationData,
                barWidth:'35%',
                itemStyle: {
                    normal: {
                        color:'#2f89cf',
                        opacity: 1,
                        barBorderRadius: 5,
                    }
                }
            }]
        };
    }

    function updateEchart5(chartInstance, chartData, district) {
        if (!chartData || !chartData.precipitation) {
            console.warn('降水量数据不完整，保持原有数据', {
                hasChartData: !!chartData,
                hasPrecipitation: !!chartData?.precipitation,
                precipitationLength: chartData?.precipitation?.length
            });
            return;
        }

        // 验证数据合理性
        const validPrecipitation = chartData.precipitation.map(precip => {
            const num = parseFloat(precip);
            return isNaN(num) || num < 0 ? Math.random() * 3 : Math.min(num, 20);
        });

        console.log('更新降水量图表，数据:', {
            precipitation: validPrecipitation,
            district: district
        });

        const option = getEchart5Option(validPrecipitation, district);
        chartInstance.setOption(option, true);
    }

    // 初始化图表6（能见度和云量）
    function initEchart6() {
        var myChart = echarts.init(document.getElementById('echart6'));

        const defaultVisibilityData = [4.8, 7.2, 8.0, 3.6, 5.3, 5.8, 4.8, 5.9, 7.9, 4.6, 7.5, 3.5,
            2.7, 3.5, 3.4, 3.4, 5.1, 3.2, 7.2, 5.1, 5.9, 6.3, 5.9, 3.1];
        const defaultCloudCoverData = [76, 78, 81, 72, 95, 96, 80, 93, 73, 96, 93, 91, 93,
            93, 82, 91, 98, 99, 75, 78, 85, 73, 79, 83];

        const option = getEchart6Option(defaultVisibilityData, defaultCloudCoverData, '郑州市');
        myChart.setOption(option);

        window.addEventListener("resize", function(){
            myChart.resize();
        });

        return myChart;
    }

    function getEchart6Option(visibilityData, cloudCoverData, district) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    lineStyle: {
                        color: '#dddc6b'
                    }
                },
                formatter: function(params) {
                    var data = params[0];
                    var index = params[0].dataIndex;
                    var cloud = cloudCoverData[index];
                    return `
                    <div style="text-align: center; padding: 8px;">
                        <div style="font-weight: bold; color: #fff; margin-bottom: 5px;">
                            ${district} - ${data.name}:00 时
                        </div>
                        <div style="color: #ffffff; font-size: 16px; margin: 5px 0;">
                           能见度: ${data.value} km
                        </div>
                        <div style="color: #ffffff; font-size: 16px; margin: 5px 0;">
                            云量: ${cloud} %
                        </div>
                    </div>
                `;
                }
            },
            grid: {
                left: '10',
                top: '20',
                right: '10',
                bottom: '10',
                containLabel: true
            },
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.2)'
                    }
                },
                data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
            }],
            yAxis: [{
                type: 'value',
                axisTick: {show: false},
                axisLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                },
                axisLabel:  {
                    textStyle: {
                        color: "rgba(255,255,255,.6)",
                        fontSize:12,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,.1)'
                    }
                }
            }],
            series: [
                {
                    name: '能见度',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 5,
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            color: '#ffffff',
                            width: 2
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(255,255,255, 0.6)'
                            }, {
                                offset: 0.8,
                                color: 'rgba(255,255,255, 0.3)'
                            }], false),
                            shadowColor: 'rgba(0, 0, 0, 0.1)',
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#ffffff',
                            borderColor: 'rgba(221, 220, 107, .1)',
                            borderWidth: 12
                        }
                    },
                    data: visibilityData
                }
            ]
        };
    }

    function updateEchart6(chartInstance, chartData, district) {
        if (!chartData || !chartData.visibility || !chartData.cloudCover) {
            console.warn('能见度或云量数据不完整，保持原有数据', {
                hasChartData: !!chartData,
                hasVisibility: !!chartData?.visibility,
                hasCloudCover: !!chartData?.cloudCover,
                visibilityLength: chartData?.visibility?.length,
                cloudCoverLength: chartData?.cloudCover?.length
            });
            return;
        }

        // 验证数据合理性
        const validVisibility = chartData.visibility.map(vis => {
            const num = parseFloat(vis);
            return isNaN(num) || num < 0 ? 5 + Math.random() * 5 : Math.min(num, 20);
        });

        const validCloudCover = chartData.cloudCover.map(cloud => {
            const num = parseInt(cloud);
            return isNaN(num) ? 50 + Math.random() * 40 : Math.max(0, Math.min(num, 100));
        });

        console.log('更新能见度图表，数据:', {
            visibility: validVisibility,
            cloudCover: validCloudCover,
            district: district
        });

        const option = getEchart6Option(validVisibility, validCloudCover, district);
        chartInstance.setOption(option, true);
    }

    // 初始化所有图表
    initAllCharts();

});